﻿import pymysql
import random
import time
import os
import requests
#控制台输出信息
def myprint(message):
    print('[%s] - %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) , message))


dbconfig = {
    'host':'localhost',
    'username':'root',
    'password':'@Aa111111..',
    'database':'zhiboba',
    'port':3319
}


class Db:

    def __init__(self , config = {}):
        self.host = config['host']
        self.username = config['username']
        self.password = config['password']
        self.database = config['database']
        self.port = config['port']
        try:
            self.db = pymysql.connect(host=self.host , 
                user=self.username , 
                password=self.password , 
                db=self.database ,
                port=self.port , 
                charset='utf8')
        except Exception as err:
            raise Exception('连接数据库失败' + str(err))

    def exe_sql(self , sql):
        self.cursor = self.db.cursor()
        try:
            res = self.cursor.execute(sql)
            self.db.commit()
            return res
        except:
            self.db.rollback()
            raise Exception('执行SQL语句出错，错误SQL:'+sql)
        finally:
            self.cursor.close()

    # sql中转义 可以用 from pymysql.converters import escape_string
    def insert_sql(self , sql):
        self.cursor = self.db.cursor()
        try:
            rs = self.cursor.execute(sql)
            insert_id = self.db.insert_id()
            self.db.commit()
            return insert_id
        except:
            self.db.rollback()
            raise Exception('执行SQL语句出错，错误SQL:'+sql)
        finally:
            self.cursor.close()

    def getdata(self , sql):
        self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor)
        try:
            self.cursor.execute(sql)
            data = self.cursor.fetchall()
            return data
        except Exception as err:
            raise Exception('没有数据返回,SQL:'+sql +' :' + str(err))
        finally:
            self.cursor.close()

    def close(self):
        self.db.close()


def mylog(message , logfile=None):
    #写入日志
    if not logfile:
        logfile = 'log.txt'
    log_path = os.path.join(os.path.dirname(__file__) , logfile)
    #判断log_path是否超过2M
    if os.path.exists(log_path):
        if os.path.getsize(log_path) > 2*1024*1024:
            os.remove(log_path)
    
    with open(log_path, 'a' , encoding="utf-8") as f:
        f.write('[%s] - %s\n' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) , message))


def get_html(url , referer=None ,timeout=30 , encoding='utf-8'):
    # 下载网页 , 增加防采集请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        'Accept-Encoding': 'gzip, deflate, br',
        
        # 连接控制
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        
        # 安全相关头（现代浏览器特征）
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-User': '?1',
        
        # 设备特征
        'Upgrade-Insecure-Requests': '1',
        'DNT': '1'  # 禁止追踪
    }
    if referer:
        headers['Referer'] = referer
    response = requests.get(url , headers=headers , timeout=timeout)
    response.encoding = encoding #
    if response.status_code == 200:
        return response.text
    return ""

if(__name__ == '__main__'):
    print("sdfsdf")